import Vue from 'vue'
import Vuex from 'vuex'
import config from "../config.js"

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		userInfo: {},
		cart: [], // 购物车
	},
	// 使用方式 this.$store.commit("setUserInfo", userInfo) 或者 ...mapMutations(['setUserInfo'])
	mutations: {
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo;
			if (userInfo.token)
				uni.setStorageSync('token', userInfo.token)
		},
		// 添加购物车
		addCartGoods(state, cartGoods) {
			let str = JSON.stringify(cartGoods.propertyMap)
			let index = state.cart.findIndex(goods => {
				return goods.goodsId == cartGoods.goodsId && JSON.stringify(goods.propertyMap) == str
			})
			if (index >= 0) state.cart[index].count += cartGoods.count
			else state.cart.push(cartGoods);
			console.log("添加购物车成功, cart: ", state.cart)
		},
	},
	actions: {}
})
